package com.canis.stockmanager.web;

import com.canis.stockmanager.comm.aop.LoggerManage;
import com.canis.stockmanager.domai.Distributor;
import com.canis.stockmanager.domai.Server;
import com.canis.stockmanager.domai.result.Combox;
import com.canis.stockmanager.domai.result.ExceptionMsg;
import com.canis.stockmanager.domai.result.ResponseData;
import com.canis.stockmanager.repository.DistributtorRepository;
import com.canis.stockmanager.repository.OperatorRepository;
import com.canis.stockmanager.utils.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/distributor")
public class DistributtorController extends BaseController {
    @Autowired
    private DistributtorRepository distributtorRepository;
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData query(Model model, @RequestParam(value = "start", defaultValue = "0") Integer start, @RequestParam(value = "sort", defaultValue = "") String sortStr,
                              @RequestParam(value = "limit", defaultValue = "10") Integer limit, Distributor distributor, HttpServletResponse response) {
        Pageable pageable = util.getPageable(sortStr,start,limit);
        Page<Distributor> pages=distributtorRepository.findByNameContainingAndPhoneContainingAndAddressContaining(distributor.getName(),distributor.getPhone(),distributor.getAddress(),pageable);

        List<Distributor> lists=pages.getContent();
        return new ResponseData(ExceptionMsg.SUCCESS, "",pages.getTotalElements(),lists);
    }
    @RequestMapping(value="/",method= RequestMethod.GET)
    public String distributor(Model model) {

        return "distributor";
    }
    @RequestMapping(value = "/queryCB", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData queryCB(Model model, @RequestParam(value = "query", defaultValue = "") String query, HttpServletResponse response) {
        Pageable pageable = util.getPageable("id",0,50);
        Page<Distributor> pages=distributtorRepository.findByNameContaining(query,pageable);
        List<Distributor> lists=pages.getContent();
        List<Combox> cbs=new ArrayList<Combox>();
        Combox cb;
        for (Distributor d:lists) {
            cb=new Combox(d.getName(),d.getId()+"");
            cbs.add(cb);
        }
        return new ResponseData(ExceptionMsg.SUCCESS, "",pages.getTotalElements(),cbs);
    }
}
